package net.zoneland.zrdp.web.impl;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;

import net.zoneland.springboot.config.SharedAppConfig;
import net.zoneland.springboot.spi.AbtractRateLimitDataProvider;
import net.zoneland.springboot.spi.RateLimitProperties;
import net.zoneland.zrdp.common.core.domain.model.LoginUser;
import net.zoneland.zrdp.framework.web.service.TokenService;

//net.zoneland.springboot.spi.RateLimitDataProvider=net.zoneland.zrdp.web.impl.RateLimitDataProviderZrdpImpl
public class RateLimitDataProviderZrdpImpl extends AbtractRateLimitDataProvider {

    @Override //TODO VIP获取从数据源中获取
    public boolean isVip(final RateLimitProperties config, final HttpServletRequest httpRequest) {
        final Collection<String> vipUids = config.getVipUids();
        if (CollectionUtils.isEmpty(vipUids)) {
            return false;
        }
        final String loginUid = getLoginedUid(httpRequest);
        return loginUid != null && vipUids.contains(loginUid);
    }

    @Override
    protected String getLoginedUid(final HttpServletRequest httpRequest) {
        final LoginUser loginUser = getLoginUser(httpRequest);
        return loginUser != null ? loginUser.getUsername() : null;
    }

    private TokenService tokenService;

    private LoginUser getLoginUser(final HttpServletRequest request) {
        return getTokenService().getLoginUser(request, false);
    }

    private TokenService getTokenService() {
        if (tokenService == null) { //此特为解决初台化循环依赖问题,特意不用@Autowired
            tokenService = SharedAppConfig.getBean(TokenService.class);
        }
        return tokenService;
    }
}
